package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Collect;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.mapper.CollectMapper;
import cn.wolfcode.trip.base.mapper.StrategyMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyServiceImpl implements IStrategyService {

    @Autowired
    private StrategyMapper strategyMapper;
    @Autowired
    private CollectMapper collectMapper;


    @Override
    public void saveOrUpdate(Strategy entity) {
        if(entity.getId()!=null){
            strategyMapper.updateByPrimaryKey(entity);
        }else {
            entity.setCollect(0);
            strategyMapper.insert(entity);
        }
    }

    @Override
    public List<Strategy> list() {
        return strategyMapper.selectAll();
    }

    @Override
    public Strategy get(Long id) {
        Strategy strategy = strategyMapper.selectByPrimaryKey(id);
        int num = collectMapper.selectCollectNum(2,null, strategy.getId());
        strategy.setStrategyNum(num);
        return strategy;
    }

    //设置收藏collect状态
    public void updateCollectById(Long id, Integer collect, Long userId) {
        //根据id设置状态为收藏/未收藏
        strategyMapper.updateCollectById(id, collect);
        Strategy strategy = strategyMapper.selectByPrimaryKey(id);
        //判断是收藏操作还是取消收藏操作
        if (collect == 1){
            Collect strategyCollect = new Collect();
            strategyCollect.setUserId(userId);
            strategyCollect.setType(2);
            strategyCollect.setCollectId(strategy.getId());
            strategyCollect.setTitle(strategy.getTitle());
            strategyCollect.setCoverUrl(strategy.getCoverUrl());
            strategyCollect.setCollectTime(new Date());
            collectMapper.insert(strategyCollect);
        } else {
            Collect strategyCollect = new Collect();
            strategyCollect.setUserId(userId);
            strategyCollect.setType(2);
            strategyCollect.setCollectId(strategy.getId());
            collectMapper.deleteByPrimaryKey(strategyCollect);
        }
    }

    @Override
    public PageInfo<Strategy> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Strategy> list = strategyMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

}
